package com.sphd.beautysalon.activitys.staff;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.Toast;

import com.rengwuxian.materialedittext.MaterialEditText;
import com.sphd.beautysalon.base.BaseActivity;
import com.sphd.beautysalon.base.RestaurantUrl;
import com.sphd.beautysalon.info.LoginInfo;
import com.sphd.beautysalon.info.RestaurantInfo;
import com.sphd.beautysalon.info.StaffInfo;
import com.sphd.beautysalon.presenter.StaffInfoPresenterImpl;
import com.sphd.beautysalon.utils.Constant;
import com.sphd.beautysalon.view.StaffInfoView;
import com.sphd.beautysalon.R;
import com.wzh.frame.utils.MyUtils;
import com.wzh.frame.utils.image.LocalImageDo;
import com.wzh.frame.views.RoundImageView;

import org.litepal.crud.DataSupport;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 添加和修改员工信息
 */
public class StaffInfoActivity extends BaseActivity implements StaffInfoView {

    private static final int TAKEPHOTO = 100;
    private static final int LOCATIONPHOTO = 101;
    private static final int ZOOMRESOULT = 102;
    private int BLANK_CODE = 0;
    private Uri imageUri;
    private Uri imageCropUri;
    File file;//原图文件
    File cropFile;//裁切图文件
    private boolean hasReceive = false;//是否存在接单员

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.staff_img)
    RoundImageView staffImg;
    @BindView(R.id.add_staff_name)
    MaterialEditText addStaffName;
    @BindView(R.id.jurisdiction_spinner)
    Spinner jurisdictionSpinner;
    @BindView(R.id.call_staff_phone)
    ImageView callStaffPhone;
    @BindView(R.id.add_staff_phone)
    MaterialEditText addStaffPhone;
    @BindView(R.id.add_staff_update_btn)
    Button addStaffUpdateBtn;
    int type = -1; //0为新增1为修改
    Intent intent;
    Bundle bundle;
    RestaurantInfo restaurantInfo;
    LoginInfo loginInfo;
    StaffInfo staffInfo;
    @BindView(R.id.content_staff_info)
    NestedScrollView contentStaffInfo;
    private String name, phone;
    boolean isFinish = false;
    boolean isManager = false;
    StaffInfoPresenterImpl staffInfoPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_staff_info);
        ButterKnife.bind(this);
        initView();
        initEvent();
    }

    private void initEvent() {
        toolbar.setNavigationOnClickListener(view -> finish());
    }

    private void initView() {
        intent = getIntent();
        bundle = intent.getExtras();
        loginInfo = DataSupport.findLast(LoginInfo.class);
        restaurantInfo = (RestaurantInfo) bundle.getSerializable(Constant.RESTAURANTSINFO);
        staffInfoPresenter = new StaffInfoPresenterImpl(this);
        type = bundle.getInt(Constant.TYPE);
        hasReceive = bundle.getBoolean(Constant.ISHAS);
        if (type == 1) {
            staffInfo = (StaffInfo) bundle.getSerializable(Constant.STAFFINFO);
            addStaffName.setText(staffInfo.getStaff_name());
            addStaffPhone.setText(staffInfo.getStaff_phone());
            setImage(staffImg, staffInfo.getStaff_photo());
            setPos(staffInfo.getStaff_auth());
            addStaffPhone.setEnabled(false);

            if (isManager(loginInfo) && staffInfo.getStaff_auth() == 3) {
                isManager = true;
                jurisdictionSpinner.setEnabled(false);
                addStaffName.setEnabled(false);
                addStaffName.setShowClearButton(false);
                addStaffPhone.setEnabled(false);

            }

            if (isCanDo()) {
                // TODO: 2016/12/23
                addStaffUpdateBtn.setVisibility(View.GONE);
                setTitleBar(toolbar, "员工信息");
            } else {
                setTitleBar(toolbar, "修改员工信息");
            }

        } else {
            setTitleBar(toolbar, "添加员工");
        }
        String path = getSDCardPath();
        file = new File(path + "/temp.jpg");
        imageUri = Uri.fromFile(file);
        cropFile = new File(getSDCardPath() + "/temp_crop.jpg");
        imageCropUri = Uri.fromFile(cropFile);


    }

    private void setPos(int staff_auth) {
        switch (staff_auth) {
            case 0:
                break;
            case 1:
                break;
            case 2:
                break;
            case 3:
                jurisdictionSpinner.setSelection(0, true);
                break;
            case 4:
                jurisdictionSpinner.setSelection(1, true);
                break;
            case 5:
                jurisdictionSpinner.setSelection(2, true);

                break;
            case 6:
                break;
            default:
                break;
        }
    }

    @OnClick({R.id.staff_img, R.id.call_staff_phone, R.id.add_staff_update_btn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.staff_img:
                showChooseDialog();
                break;
            case R.id.call_staff_phone:
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                        context);
                // set dialog message
                alertDialogBuilder
                        .setTitle("提示")
                        .setMessage("是否给:" + addStaffPhone.getText().toString() + "拨打电话")
                        .setCancelable(false)
                        .setPositiveButton("确定",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {

                                        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + addStaffPhone.getText().toString()));
                                        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                                            // TODO: Consider calling
                                            toast("没有对应的电话权限，请开启后使用！");
                                            return;
                                        }
                                        startActivity(intent);

                                    }
                                })
                        .setNegativeButton("取消",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        dialog.cancel();
                                    }
                                });

                // create alert dialog
                AlertDialog alertDialog = alertDialogBuilder.create();

                // show it
                alertDialog.show();
                break;
            case R.id.add_staff_update_btn:
                if (getMessage()) {
                    Map<String, String> map = new HashMap<>();
                    List<File> fileList = new ArrayList<>();
                    fileList.add(cropFile);

                    map.put("name", addStaffName.getText().toString().trim());
                    map.put("auth", (jurisdictionSpinner.getSelectedItemPosition() + 3) + "");
                    if (type != 0) {
                        map.put("staffid", String.valueOf(staffInfo.getId()));
                        //传入修改员工信息的Url
                        if (isFinish) {
                            staffInfoPresenter.sendMapAndFile(RestaurantUrl.Httptitle + RestaurantUrl.ChangeStaff, "image", fileList, map);
                        } else {
                            staffInfoPresenter.sendMap(RestaurantUrl.Httptitle + RestaurantUrl.ChangeStaff, map);
                        }

                    } else {
                        map.put("cgid", String.valueOf(restaurantInfo.getId()));
                        map.put("phone", addStaffPhone.getText().toString().trim());
                        //传入新增员工的Url
                        if (isFinish) {
                            staffInfoPresenter.sendMapAndFile(RestaurantUrl.Httptitle + RestaurantUrl.AddStaff, "image", fileList, map);
                        } else {
                            staffInfoPresenter.sendMap(RestaurantUrl.Httptitle + RestaurantUrl.AddStaff, map);

                        }
                    }

                }
                break;
        }
    }

    @Override
    public void recRes(int res) {
        if (res == 1) {
            toast("提交成功");
            setResult(1);
            finish();
        } else {
            toast("提交失败，请重试！");
        }
    }

    private void showChooseDialog() {

        LocalImageDo localImageDo = new LocalImageDo(contentStaffInfo, this);
        localImageDo.setOnClickButtonListener(new LocalImageDo.OnClickButtonListener() {
            @Override
            public void OnClick(View view, PopupWindow popupWindow) {
                if (view.getId() == R.id.camara) {
                    takePhoto();
                } else if (view.getId() == R.id.photo) {
                    chooseFromGallery();
                }
                popupWindow.dismiss();
            }
        });
        localImageDo.showPopuWindow();
    }

    /**
     * 从相册选择图片
     */
    private void chooseFromGallery() {
        //构建一个内容选择的Intent
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, LOCATIONPHOTO);
    }

    /**
     * 打开相机的时候确定此张图片的名字
     */
    private void takePhoto() {
        Intent intent = null;
        intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//action is capture
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, TAKEPHOTO);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case TAKEPHOTO:
                cropImg(imageUri);
                break;
            case LOCATIONPHOTO:
                if (data == null) {
                    return;
                } else {
                    //获取到用户所选图片的Uri
                    imageUri = data.getData();
                    cropImg(imageUri);
                }
                break;
            case ZOOMRESOULT:
                Bundle extras = data.getExtras();
                if (extras != null) {
                    try {
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageCropUri));
                        staffImg.setImageBitmap(bitmap);
                        isFinish = true;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;

        }
    }

    private void cropImg(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 700);
        intent.putExtra("outputY", 700);
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageCropUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, ZOOMRESOULT);
    }

    //p判断 填写员工数据是否为空
    private boolean getMessage() {
        boolean isEmpty = false;

        if (!TextUtils.isEmpty(addStaffName.getText())) {
            isEmpty = true;
            name = addStaffName.getText().toString().trim();
        } else {
            Toast.makeText(context, "姓名不能为空", Toast.LENGTH_SHORT).show();
            isEmpty = false;
            return isEmpty;
        }
        if (!TextUtils.isEmpty(addStaffPhone.getText()) &&
                MyUtils.isMobileNO(addStaffPhone.getText().toString().trim())) {

            isEmpty = true;
            phone = addStaffPhone.getText().toString().trim();

        } else {
            Toast.makeText(context, "手机号填的不正确", Toast.LENGTH_SHORT).show();
            isEmpty = false;
            return isEmpty;
        }

        if (jurisdictionSpinner.getSelectedItemPosition() == -1) {
            Toast.makeText(context, "点击选取角色", Toast.LENGTH_SHORT).show();
            isEmpty = false;
            return isEmpty;
        } else {
            if (jurisdictionSpinner.getSelectedItemPosition() == 0) {
                if (!isManager) {
                    toast("店长不能在此编辑");
                    isEmpty = false;
                    return isEmpty;
                }else {
                    isEmpty = true;
                    return isEmpty;
                }


            } else if (jurisdictionSpinner.getSelectedItemPosition() == 1) {
                if (hasReceive) {
                    //如果已经有接单员
                    //如果是在新增的情况下
                    if (type == 0) {
                        toast("已有接单员，请勿重复原则");
                        isEmpty = false;
                        return isEmpty;
                    } else {
                        //如果是修改员工信息
                        if (staffInfo.getStaff_auth() == 4) {
                            isEmpty = true;
                            return isEmpty;
                        } else {
                            toast("已有接单员，请勿重复原则");
                            isEmpty = false;
                            return isEmpty;
                        }
                    }

                } else {
                    isEmpty = true;
                    return isEmpty;
                }
            }


        }


        return isEmpty;

    }

    public static String getSDCardPath() {
        String cmd = "cat /proc/mounts";
        Runtime run = Runtime.getRuntime();// 返回与当前 Java 应用程序相关的运行时对象
        try {
            Process p = run.exec(cmd);// 启动另一个进程来执行命令
            BufferedInputStream in = new BufferedInputStream(p.getInputStream());
            BufferedReader inBr = new BufferedReader(new InputStreamReader(in));

            String lineStr;
            while ((lineStr = inBr.readLine()) != null) {
                // 获得命令执行后在控制台的输出信息
                if (lineStr.contains("sdcard")
                        && lineStr.contains(".android_secure")) {
                    String[] strArray = lineStr.split(" ");
                    if (strArray != null && strArray.length >= 5) {
                        String result = strArray[1].replace("/.android_secure",
                                "");
                        return result;
                    }
                }
                // 检查命令是否执行失败。
                if (p.waitFor() != 0 && p.exitValue() == 1) {
                    // p.exitValue()==0表示正常结束，1：非正常结束
                }
            }
            inBr.close();
            in.close();
        } catch (Exception e) {

            return Environment.getExternalStorageDirectory().getPath();
        }

        return Environment.getExternalStorageDirectory().getPath();
    }

    private boolean isCanDo() {


        return (isCg_has_storemanager(restaurantInfo) && isSuperManager(loginInfo));
    }

    @Override
    public void showLoading() {
        showLoadingDialog();
    }

    @Override
    public void dissLoading() {
        dissLoadingDialog();
    }
}
